package com.nanbei.stack;

import java.util.Iterator;

/**
 * @ClassDescription: 链表实现栈操作
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/24 14:13
 */
public class LinkStack<E> implements StackInterface<E>,Iterable<E> {



    /**
     * 定义链表节点
     *
     * @param <E> 泛型
     */
    private static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    //创建一个哨兵节点、一个头指针、一个尾指针。让头尾指针都指向哨兵节点。
    Node<E> sentinel = new Node<E>(null, null);
    Node<E> head = sentinel;
    private int size = 0;
    private final int capacity;

    public LinkStack(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }

        //创建一个新节点
        Node<E> node = new Node<>(value, null);
        // 因为head节点在栈顶元素的上一个元素，所以新增节点的next指针因该指向 head.next 即栈顶元素
        node.next = head.next;
        // 新增元素指向栈顶元素后 head节点需要向上移动一位。
        head.next= node;
        size++;

        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }

        Node<E> node = head.next;
        head.next = node.next;
        size--;
        return node.value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p!=null;
            }

            @Override
            public E next() {
                E value = p.value;
                p=p.next;
                return value;
            }
        };
    }

}
